<!-- 新增与编辑供应商 -->
<template>
  <el-dialog :title="modalData.title" :visible.sync="dialog.show" center width="1230px" height="400px" custom-class="mydialog" append-to-body @close="handleClose">
    <div class="dialog-content">
      <el-form ref="formWorkerServicetype" :model="form" :rules="rules" label-width="150px" >
        <el-row :gutter="12" type="flex" justify="center">
          <el-col :span="12">
            <el-form-item label="名称：" prop="serviceTypeName">
              <el-input v-model="form.serviceTypeName" maxlength="50"/>
            </el-form-item>
            <el-form-item label="品类：" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="选择品类" class="seach-select" size="small">
                <el-option v-for="item in modalStaticData.categoryList " :key="item.categoryId" :label="item.categoryName" :value="item.categoryId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="品牌：" prop="lianbaoBrandId">
              <el-select v-model="form.lianbaoBrandId" placeholder="选择品牌" class="seach-select" size="small">
                <el-option v-for="item in modalStaticData.lianbaoBrandList " :key="item.brandId" :label="item.brandName" :value="item.brandId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="价格：" prop="price">
              <el-input v-model="form.price" maxlength="50"/>
            </el-form-item>
            <!-- prop="serviceTypeOrder" -->
            <el-form-item label="排序：" >
              <el-input v-model="form.serviceTypeOrder" maxlength="50"/>
            </el-form-item>
            <el-form-item label="原价：" prop="originalPrice">
              <el-input v-model="form.originalPrice" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保内保外专用：" prop="inGuaranteePeriod">
              <el-radio v-model="form.inGuaranteePeriod" label="Y">保内</el-radio>
              <el-radio v-model="form.inGuaranteePeriod" label="N">保外</el-radio>
            </el-form-item>
            <el-form-item label="工单服务类型：" >
              <el-radio v-model="form.orderServiceType" label="维修">维修</el-radio>
              <el-radio v-model="form.orderServiceType" label="安装">安装</el-radio>
              <el-radio v-model="form.orderServiceType" label="保养">保养</el-radio>
              <el-radio v-model="form.orderServiceType" label="移机">移机</el-radio>
              <el-radio v-model="form.orderServiceType" label="清洗">清洗</el-radio>
            </el-form-item>

            <el-form-item label="服务类型描述：" >
              <el-input
                v-model="form.serviceTypeContent"
                :rows="3"
                type="textarea"
                maxlength="1000"/>
            </el-form-item>
            <el-form-item label="服务图片" prop="logo">
              <el-upload
                ref="uploadImage"
                :auto-upload="false"
                :show-file-list="false"
                :on-preview="handlePictureCardPreview"
                :file-list="imageFileList"
                :on-change="logoChange"
                :on-remove="logoRemove"
                action="string"
                class="avatar-uploader">
                <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="text-center mt-30">
        <el-button class="greenbt bt-wd" type="primary" @click="saveFun('formWorkerServicetype')">保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import {
  post
} from '@/api/utils'
import { checkPhone } from '@/utils/utils'
export default{
  props: {
    modalStaticData: {
      type: Object,
      default: () => {}
    },
    // 父组件调用时传进来的参数
    modalData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    var validateMallCostPrice = (rule, value, callback) => {
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
      if (reg.test(value) || !value) {
        callback()
      } else {
        callback(new Error('请输入正确的价格'))
      }
    }

    var phoneValidate = (rule, value, callback) => {
      checkPhone(value) ? callback() : callback(new Error('请输入正确的手机号'))
    }

    return {
      imageFileList: [],
      dialogImageUrl: '',
      dialog: {
        title: '', show: true
      },
      form: {
        'serviceTypeId': null, 'serviceTypeName': null, 'serviceTypeOrder': null, 'lianbaoBrandId': null, 'categoryId': null,
        'price': null, 'inGuaranteePeriod': null, 'orderServiceType': null,
        'originalPrice': null, 'serviceTypeContent': null
      },
      rules: {
        serviceTypeName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 50, message: '长度在 50 个字符内', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择品类', trigger: 'blur' }
        ],
        lianbaoBrandId: [
          { required: true, message: '请选择品牌', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { required: true, validator: validateMallCostPrice, trigger: 'blur' }
        ],
        inGuaranteePeriod: [
          { required: true, message: '请选择保内保外', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '请输入联系人名称', trigger: 'blur' },
          { max: 50, message: '长度在 50 个字符内', trigger: 'blur' }
        ],
        originalPrice: [
          { validator: validateMallCostPrice, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号名称', trigger: 'blur' },
          { max: 50, message: '长度在 50 个字符内', trigger: 'blur' },
          { validator: phoneValidate, trigger: 'blur' }
        ],
        supplierTypeItme: [
          { required: true, message: '请选择出货方式', trigger: 'change' }
        ]

      },
      supplierTypeList: [{ label: '商城供应商', value: 1 }, { label: '网批供应商', value: 2 }]

    }
  },
  created: function() {
    if (this.modalData.servicetype) {
      var servicetype = this.modalData.servicetype

      this.form = { ...this.form, ...servicetype, 'lianbaoBrandId': parseInt(servicetype.lianbaoBrand.id), 'categoryId': parseInt(servicetype.category.id), 'price': servicetype.outGuaranteePrice }
      this.dialogImageUrl = servicetype.photo
      this.form = Object.assign({}, this.form, {})
    }
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },

    logoChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        this.$refs.uploadImage.clearFiles()
        this.$message.error('上传头像图片大小不能超过 1M')
        return false
      }

      this.imageData = file.raw
      this.imageFileList = []
      this.imageFileList.push(file)
      if (file) {
        // console.log(file)
        this.dialogImageUrl = URL.createObjectURL(file.raw)
      }
    },

    handlePictureCardPreview(file) {
      if (file) {
        this.dialogImageUrl = URL.createObjectURL(file.raw)
        this.dialogVisible = true
      }
    },

    logoRemove(file, fileList) {
      this.imageData = null
      this.imageFileList = fileList
    },

    saveFun(formName) {
      const self = this
      // console.log(formName)
      // console.log(self.$refs[formName])
      self.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(valid)

          var form = this.form

          var formData = new FormData()
          for (var i in form) {
            if (form[i]) {
              formData.append(i, form[i])
            }
          }

          if (this.imageFileList[0]) {
            formData.append('iamges', this.imageFileList[0] ? this.imageFileList[0].raw : null)
          }

          var url = '/webpoint/workerServicetype/save'

          var headers = { 'Content-Type': 'multipart/form-data;', 'Accept': 'application/json' }

          post('/wxh-site-rest/rest/', url, formData, headers).then(response => {
            if (response.data.status === 'success') {
              console.log(response)
              this.$message({
                message: '编辑供应商成功'
              })
              console.log(1111111111)
              this.modalStaticData.closeChildAndRefresh()
            } else if (response.data.status === 'token_check_faild') {
              this.$message({
                message: response.data.messge,
                type: 'warning'
              })
            }
          }).catch(error => {
            console.log(error)
            this.$message({
              message: '数据加载失败',
              type: 'warning'
            })
          })
        } else {
          return false
        }
      })
    }

  }
}
</script>

<style>
  .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.tinymce-content {
  min-width: 700px;
  max-width: 800px;
}
.logo {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  font-size: 40px;
}
.position-absolute{
  z-index: 9;
  position: absolute;
};

.el-card .el-card_children,.children_t{
  display: block;
  margin-top: 200px;
  display: flex;
  width: 100%;
}

</style>
